package com.bringspring.oauth.method.dingdingH5.granter;

import com.bringspring.oauth.method.detail.UserDetailsServiceImpl;
import com.bringspring.oauth.method.dingdingH5.token.DingTalkH5AuthenticationToken;
import lombok.SneakyThrows;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;

import java.util.Map;

public class DingTalkH5AbstractTokenGranter extends AbstractTokenGranter {

    private final UserDetailsServiceImpl userDetailsService;
    private static final String GRANT_TYPE = "DingTalkH5";
    private final AuthenticationManager authenticationManager;

    public DingTalkH5AbstractTokenGranter(UserDetailsServiceImpl userDetailsService, AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService, OAuth2RequestFactory requestFactory) {
        super(tokenServices, clientDetailsService, requestFactory, GRANT_TYPE);
        this.authenticationManager = authenticationManager;
        this.userDetailsService = userDetailsService;

    }

    @SneakyThrows
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {
        Map<String, String> requestParameters = tokenRequest.getRequestParameters();
        String code = requestParameters.get("code");
        UserDetails u = userDetailsService.loadUserByDingCodeH5(code);
        DingTalkH5AuthenticationToken dingTalkH5AuthenticationToken = new DingTalkH5AuthenticationToken(code, u.getUsername(), u.getPassword());
        dingTalkH5AuthenticationToken.setDetails(requestParameters);
        OAuth2Request oAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(oAuth2Request, dingTalkH5AuthenticationToken);
    }
}
